﻿using System;
using System.Collections.Generic;
using System.Text;
using SimpleOrmCFPC.Core.Query.Where;
using SimpleOrmCFPC.Core.Query.expressions.ExprssionCompilers;

namespace SimpleOrmCFPC.Core.Query
{
    public class WhereToSqlBuilder
    {
        public void Visit(OperatorWhereElement element, StringBuilder builder, List<object> parameters)
        {
            builder.Append("(");
            bool first = true;
            foreach (IWhereElement parameter in element.Operands)
            {
                if (!first)
                    builder.Append(" " + element.Op + " ");
                first = false;
                parameter.Visit(this, builder, parameters);

            }
            builder.Append(")");
        }

        public void Visit(SimpleWhereElement element, StringBuilder builder, List<object> parameteres)
        {
            builder.Append(element.Text);
            parameteres.AddRange(element.Values);
        }

        public void Visit(CastWhereElement element, StringBuilder builder, List<object> parameters)
        {
            var p = new List<object>();
            element.Element.Visit(this, builder, p);
            if (p.Count != 0)
                parameters.Add(Convert.ChangeType(p[0], element.Type, null));
        }

        public void Visit(VariableAccessWhereElement element, StringBuilder builder, List<object> parameters)
        {
            builder.Append("?");
            var p = new List<object>();
            element.Element.Visit(this, builder, p);
            parameters.Add(p[0]);
        }
    }
}